package com.cygnus.controller;

import com.cygnus.model.Employee;
import com.cygnus.model.Msg;
import com.cygnus.service.EmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

@Controller
public class EmployeeController {
    @Autowired
    EmployeeService employeeService;

    @RequestMapping(value = "/empsj",method = RequestMethod.GET)
    @ResponseBody
    public Msg returnEmpsInJson
            (@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum){
        //        要实现分页，首先需要调用PageHelper.startPage，传入页码pn和每一页的记录数pageSize
        PageHelper.startPage(pageNum,5);
//        而后startPage下一句的查询就会是一个分页查询
        List<Employee> employees = employeeService.getAll();

/*        还可以使用pageinfo包装查询结果，将其中封装的详细分页信息交给页面:
            navigatePages:导航栏页数
 */
/*      employees会被保存在PageInfo的父类PageSerializable的属性 protected List<T> list 中
        要得到employees，通过getList()。绝非PageInfo.employees
 */
        PageInfo employeePageInfo = new PageInfo(employees,5);
        employeePageInfo.isHasPreviousPage();

        return Msg.success().add("pageInfo",employeePageInfo);
    }


    //新增 逻辑
    @ResponseBody
    @RequestMapping(value = "/empsj" ,method = RequestMethod.POST)
    public Msg saveEmp(@Valid Employee employee, BindingResult bindingResult){
        boolean result=employeeService.validateName(employee.getEmpName());
        HashMap<String, Object> map = new HashMap<>();
        if (bindingResult.hasErrors()){
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError:fieldErrors
                 ) {
                map.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
            return Msg.fail().add("ErrorFields",map);
        }
        if (!result){
            map.put("empName", "老子自己写的Hibernate后端验证说的：用户名重复");
            return Msg.fail().add("ErrorFields",map);
        }
        else {
            employeeService.saveEmp(employee);
            return Msg.success();
        }
    }

    //AJAX校验逻辑（用户名排重）
    @ResponseBody
    @RequestMapping(value = "/validateName")
    public Msg validate(@RequestParam("empName") String empName){
        //先校验正则
        String reg="(^[a-zA-Z0-9_-]{6,15}$)|(^[\\u4e00-\\u9fa5·]{2,10})";
        boolean matches = empName.matches(reg);
        if (!matches){
            return Msg.fail().add("matches_msg","AJAX后端：用户名必须是6到15位英文数字组合或2到10位中文");
        }
        //正则满足，再查重
        boolean result=employeeService.validateName(empName);
        if (result){
            return Msg.success().add("matches_msg","AJAX后端：用户名不重复可以用");
        }
        else return Msg.fail().add("matches_msg","AJAX后端：用户名已重复");
    }
    //AJAX校验逻辑（邮箱格式校验）
    @ResponseBody
    @RequestMapping(value = "/validateEmail")
    public Msg validateEmail(@RequestParam("email") String email){
        //先校验正则
        String reg="^[A-Za-z0-9\\u4e00-\\u9fa5]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
        boolean matches = email.matches(reg);
        if (!matches){
            return Msg.fail().add("matches_msg","AJAX后端：邮箱名非法");
        }

        else  return Msg.success().add("matches_msg","AJAX后端：可以使用的邮箱名");

    }

    //                      改           逻辑

//                     查询要修改的员工的数据,回显
    @ResponseBody
    @RequestMapping(value = "/empsj/{id}",method = RequestMethod.GET)

    public Msg getEmp(@PathVariable("id") Integer id){
        Employee employee=employeeService.getEmp(id);
        return Msg.success().add("emp", employee);
    }

    //                   后端校验、  业务逻辑
    @ResponseBody
    @RequestMapping(value = "/empsj/{empId}" ,method = RequestMethod.PUT)
    public Msg updateEmp(@Valid Employee employee, BindingResult bindingResult){
        HashMap<String, Object> map = new HashMap<>();
        boolean result=employeeService.validateName(employee.getEmpName());
        if (bindingResult.hasErrors()){
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError:fieldErrors
            ) {
                map.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
            return Msg.fail().add("ErrorFields",map);
        }
        if (!result){
            map.put("empName", "Hibernate后端验证：用户名重复");
            return Msg.fail().add("ErrorFields",map);
        }
        else {
            System.out.println("将要更新的员工数据："+employee);
            employeeService.updateEmp(employee);
            return Msg.success();
        }
    }

    //                              删 逻辑
    //      单个/批量删除  二合一
    @ResponseBody
    @RequestMapping(value = "/empsj/{ids}", method = RequestMethod.DELETE)
    public Msg deleteEmp(@PathVariable("ids") String ids){
        if (!ids.contains("-")){
            Integer id=Integer.parseInt(ids);
            employeeService.deleteEmp(id);
        }
        else {
            String[] split_ids = ids.split("-");
            List<Integer> idList = new ArrayList<>();
            for (String s:split_ids
                 ) {
                idList.add(Integer.parseInt(s));
            }
            employeeService.deleteInBulk(idList);
        }
        return Msg.success();
    }

}
